import config from "@/utils/config.js";

let {
	HEADER,
	TOKENNAME,
	Private_key,
	SiteBaseUrl,
	prourl
}  = config;


import md5 from './md5.js';
import store from './../store'; //vuex
import sj_show_modal from './../components/G_show_modal/index.js'
// import {decrypt,encrypt} from "@/utils/encoded.js";

let num = 0;
const showModal = (op = {}) => {
	console.info("ddd");
	// #ifdef APP-PLUS
	return new Promise((resolve, reject) => {
		ssm = new sj_show_modal({
			...op,
			$event: (e) => {
				if (e.res) {
					resolve(e);
				} else {
					reject(e);
				}
			}
		})
		ssm.show();
	
	})
	// #endif
	
	// #ifndef APP-PLUS
	return	new Promise((resolve, reject)=>{
		ssm = uni.showModal({
		    title: op.title,
		    content: op.concent,
			confirmText:op.confirmVal,
			cancelText:op.cancelVal,
		    success:  (res)=> {
		        if (res.confirm) {
					resolve();
		        } else if (res.cancel) {
					reject();
		        }
		    },
			fail:(err)=> {
				console.info("err",err);
			}
		});
	})
	// #endif
}



//const isjiami = true;

// const isjiami = true;
const isjiami = false;

/**
 * 发送请求
 * 
 * 参数1:url地址
 * 参数2:请求的方法
 * 参数3:请求的数据
 * 参数4: 特殊参数 判断是否需要 授权 需要鉴权 noVerify为 true 的时候 不验证 返回的code
 * noAuth 为 false 验证授权 true 不验证授权
 * 
 * 
 */


let request = async  function request(api, method, data, {
	noAuth = false,
	noVerify = false,
	isopr = false,
	
}) {
	
	
	// let remoteIP = await config.requestRemoteIp(); // 动态设置接口请求域名
	
	let {
		HEADER,
		TOKENNAME,
		Private_key,
	}  = config;
	
	let {SiteBaseUrl,prourl} = config.baseUrl;
	
	// console.info("------------------------");
	// console.info("config",config.baseUrl.pro);
	// console.info("config",config.baseUrl.SiteBaseUrl);
	// console.info("------------------------");
	
	let noVerify1 = false;
	let Url = SiteBaseUrl;
	let header = HEADER;
	if(isopr){
		Url = prourl;
	}
	let token = wx.getStorageSync("token");
	if (!noAuth) {
		//登录过期自动登录
		
		if ( !token ) { //checkLogin 应该是验证登录的方法
			//验证成功继续请求自己的接口  授权方法 授权完了之后继续请求
			// console.info("未登录aaa");
			// return new Promise((ret,rej)=>{ret({"code":401,"msg":"请登录后操作","time":"1639115311","data":null})});
		} else {

		}
	}
	header['token'] = wx.getStorageSync("token");
	header['timestamp'] = Date.parse(new Date())/1000;
	
	// console.info("token",wx.getStorageSync("token"));
	// console.info("token",token);
	// console.info("header",header);
	
	// login_type =》wechat=小程序    app
	// #ifdef MP-WEIXIN
	header['login-type'] =  'wechat';
	// #endif
	
	// #ifndef MP-WEIXIN
	header['login-type'] =  'app';
	// #endif
	
	// console.info("urls",Url + api);
	// let area_id = uni.getStorageSync("area_id");
	// if(area_id && !data.area_id && api.indexOf("address")==-1){
	// 	data.area_id = area_id;//城市id
	// }
	
	//签名操作
	header['sign'] =  encodeSign(data);;
	
	//提交前加密
	if(isjiami){
		console.info(data,"data");
		let objdata = data;
		objdata = JSON.stringify(objdata);
		let jiami = "";
		// let jiami = encrypt(objdata);
		jiami = jiami.toString();
		data = {body:jiami}
		console.info("data加密",data);  
	}
	
	return new Promise((reslove, reject) => {
		uni.request({
			url: Url + api,
			method: method || 'GET',
			header: header,
			data: data || {},
			success: (res1) => {
				// console.info("header",header);
				// console.info("res1",res1);
				let resa = "";
				let res = res1;
				if(isjiami){
					if(res1.data.data){
						if(res1.data.data.body){
							// resa = decrypt(res1.data.data.body);//解密
							resa = JSON.parse(resa);
							res1.data.data = resa;
							// res1.data.data.body = null;
							res = res1;
						}
					}
					console.info("res解密",res);
				}
				
				
				if (res.statusCode == 401) {
					//没有登录
					uni.setStorageSync('userInfo', {});
					uni.setStorageSync('token', '');
					uni.setStorageSync('session_key', '');
					// uni.switchTab({
					// 	url:"/pages/index/index"
					// })
					console.info(res,"res??");
					// #ifdef APP-PLUS
					showModal({
						title:'温馨提示',
						concent:'检测到您未登录或登录信息已过期',
						delCancel:true,
						confirmVal:'去授权',
						cancelVal:"先逛逛",
					}).then(res=>{
						uni.hideLoading();
						uni.reLaunch({
							url: '/pagesim/center/login'
						})
						num=0;
					}).catch(err=>{
						uni.hideLoading();
						num=0;
					})
					// #endif
					
					
					reslove(res.data, res);
					return false;
				}
				if (noVerify1)
					reslove(res.data, res);
				else if (res.data.code == 1)
					reslove(res.data, res);
				else if (res.data.code == 201) {
					console.info("进来了？");
					uni.setStorageSync('userInfo', {});
					uni.setStorageSync('token', '');
					uni.setStorageSync('session_key', '');
					reslove(res.data, res);
				} else if ([410000, 410001, 401, 410002, 401].indexOf(res.data.code) !== -1) {
					//退出登录?
					uni.setStorageSync('userInfo', {});
					uni.setStorageSync('token', '');
					uni.setStorageSync('session_key', '');
					reslove(res.data, res);
				} else
					reslove(res.data, res);
			},
			fail: (res) => {
				console.info("请求失败!!!0", res);
				if (res.statusCode == 401) {
					//没有登录
					uni.setStorageSync('userInfo', {});
					uni.setStorageSync('token', '');
					uni.setStorageSync('session_key', '');
					uni.switchTab({
						url:"/pages/index/index"
					})
					reslove(res.data, res);
					return false;
				}else{
					uni.showToast({
						icon:"none",
						duration:5000,
						title:"请检查网络状态.....",
					})
					reject('请求失败');
				}
				
			}
		})
	});
}

export default request;


//生成签名方法
//生成签名
function encodeSign (params = {}) {
  var tmp = {};
  Object.keys(params).sort().forEach(function (k) {
    tmp[k] = params[k]
  });
  let private_key = md5(Private_key);//密钥是这个字符串md5后的
  let token = store.state.token;
  let sign_str = private_key;
  for (var index in tmp) {
    //如值为数组转成字符串
    if (typeof tmp[index] === 'object'){
      tmp[index] = JSON.stringify(tmp[index]);
	  continue;//对象数据不比对
    }
	if(tmp[index]==undefined){
		continue;//undefined数据不比对
	}
    if (token != undefined  && token!=""){
      sign_str += index + tmp[index] + token;
    }else{
      if (tmp[index] != undefined) {
         sign_str += index + tmp[index] ;
      }
    }
  }
  sign_str += private_key;
  // console.info("sign_str",sign_str);
  sign_str = md5(sign_str);
  return sign_str;
}




['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt) => request(api, method, data, opt || {})
});
